給定一個羅馬數字,將其轉換為整數。
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
解題:
觀察CM = 900, XC = 90 and IV = 4
當前字母 < 後面的字母 , 則減去該數值 ,反之,若是大於後面的值,則加總該數。使用next要注意超出陣列的問題。
RomanValue = {
"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000
}
def roman_to_int(s)
(0..(s.length-1)).sum{ |index|
if RomanValue[s[index.next]].nil?
RomanValue[s[index]] * 1
else
if RomanValue[s[index]] < RomanValue[s[index.next]]
RomanValue[s[index]] * -1
else
RomanValue[s[index]] * 1
end
end
}
end
如果要寫乾淨一點,可以使用fetch方法,加入預設值,減少判斷
def roman_to_int(s)
(0..(s.length-1)).sum{ |index|
if RomanValue[s[index]] < RomanValue.fetch(s[index.next],0)
RomanValue[s[index]] * -1
else
RomanValue[s[index]] * 1
end
}
end